<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="600px" :title="drawerTitle">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="work-order-form"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工单编码" prop="workOrderCode">
            <el-input
              v-model="formData.workOrderCode"
              placeholder="请输入工单编码"
              clearable
              :disabled="isEdit"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="产品型号" prop="productModel">
            <el-input
              v-model="formData.productModel"
              placeholder="请输入产品型号"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="计划数量" prop="plannedQuantity">
            <el-input-number
              v-model="formData.plannedQuantity"
              :min="1"
              :max="999999"
              placeholder="请输入计划数量"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="工艺路线编码" prop="routeCode">
            <el-input
              v-model="formData.routeCode"
              placeholder="请输入工艺路线编码（可选）"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="产线编码" prop="productionLineCode">
            <el-input
              v-model="formData.productionLineCode"
              placeholder="请输入产线编码（可选）"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="isEdit">
        <el-col :span="24">
          <el-form-item label="工单状态">
            <el-tag :type="getStatusType(formData.status)">
              {{ getStatusText(formData.status) }}
            </el-tag>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="isEdit && formData.completedQuantity">
        <el-col :span="24">
          <el-form-item label="完成数量">
            <span>{{ formData.completedQuantity }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        {{ isEdit ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="workOrderForm">
import { ref, reactive, computed } from "vue";
import { ElMessage, type FormInstance } from "element-plus";
import { createWorkOrder, getWorkOrderById, updateWorkOrder, type WorkOrder } from "@/api/modules/workorder";

// 抽屉参数接口
interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<WorkOrder.WorkOrderListItem>;
  getTableList?: () => void;
}

const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const drawerVisible = ref(false);

// 抽屉属性
const drawerProps = ref<DrawerProps>({
  title: "",
  isView: false,
  row: {}
});

// 判断是否为编辑模式
const isEdit = computed(() => drawerProps.value.title === "编辑");

// 抽屉标题
const drawerTitle = computed(() => `${drawerProps.value.title}工单`);

// 表单数据
const formData = reactive<Partial<WorkOrder.WorkOrderListItem>>({
  id: undefined,
  workOrderCode: '',
  productModel: '',
  plannedQuantity: undefined,
  routeCode: '',
  productionLineCode: '',
  status: '',
  completedQuantity: undefined
});

// 表单验证规则
const rules = reactive({
  workOrderCode: [
    { required: true, message: "请输入工单编码", trigger: "blur" }
  ],
  productModel: [
    { required: true, message: "请输入产品型号", trigger: "blur" }
  ],
  plannedQuantity: [
    { required: true, message: "请输入计划数量", trigger: "blur" }
  ]
});

// 获取状态类型
const getStatusType = (status: string | undefined): "success" | "primary" | "warning" | "info" | "danger" => {
  if (!status) return 'info';
  const statusMap: Record<string, "success" | "primary" | "warning" | "info" | "danger"> = {
    'CREATED': 'info',
    'RELEASED': 'warning',
    'STARTED': 'primary',
    'SUSPENDED': 'warning',
    'COMPLETED': 'success',
    'CLOSED': 'info',
    'CANCELLED': 'danger'
  };
  return statusMap[status] || 'info';
};

// 获取状态文本
const getStatusText = (status: string | undefined): string => {
  if (!status) return '';
  const statusMap: Record<string, string> = {
    'CREATED': '已创建',
    'RELEASED': '已下达',
    'STARTED': '生产中',
    'SUSPENDED': '已暂停',
    'COMPLETED': '已完成',
    'CLOSED': '已关闭',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
};

// 获取工单详情
const getWorkOrderDetail = async (id: string) => {
  try {
    const res = await getWorkOrderById(id);
    Object.assign(formData, res.data);
  } catch (error) {
    console.error('获取工单详情失败:', error);
    ElMessage.error('获取工单详情失败');
  }
};

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: undefined,
    workOrderCode: '',
    productModel: '',
    plannedQuantity: undefined,
    routeCode: '',
    productionLineCode: '',
    status: '',
    completedQuantity: undefined
  });
};

// 接收父组件传过来的参数
const open = async (params: DrawerProps) => {
  drawerProps.value = params;
  
  if (params.title === "编辑" || params.title === "查看") {
    // 编辑和查看模式，直接使用传入的数据
    Object.assign(formData, params.row);
  } else {
    // 新增模式，重置表单
    resetFormData();
  }
  
  drawerVisible.value = true;
};

// 提交表单
const handleSubmit = () => {
  if (drawerProps.value.isView) return;
  
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      if (isEdit.value && formData.id) {
        // 编辑模式 - 调用更新接口
        const params: WorkOrder.CreateWorkOrderRequest = {
          workOrderCode: formData.workOrderCode!,
          productModel: formData.productModel!,
          plannedQuantity: formData.plannedQuantity!,
          routeCode: formData.routeCode,
          productionLineCode: formData.productionLineCode
        };
        await updateWorkOrder(formData.id, params);
        ElMessage.success('工单更新成功');
      } else {
        // 新增模式
        const params: WorkOrder.CreateWorkOrderRequest = {
          workOrderCode: formData.workOrderCode!,
          productModel: formData.productModel!,
          plannedQuantity: formData.plannedQuantity!,
          routeCode: formData.routeCode,
          productionLineCode: formData.productionLineCode
        };
        await createWorkOrder(params);
        ElMessage.success('工单创建成功');
      }
      
      // 刷新父组件列表
      drawerProps.value.getTableList?.();
      drawerVisible.value = false;
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error(isEdit.value ? '工单更新失败' : '工单创建失败');
    } finally {
      submitLoading.value = false;
    }
  });
};

// 取消操作
const handleCancel = () => {
  drawerVisible.value = false;
};

// 暴露方法给父组件
defineExpose({
  open
});
</script>

<style scoped>
.content-box {
  padding: 20px;
}

.form-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.form-header h2 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.work-order-form {
  max-width: 800px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>